<template>
  <div class="seckill-list-container">
    <el-card class="search-card">
      <el-form :model="formInline" label-width="100px" inline>
        <el-form-item label="活动名称">
          <el-input v-model="formInline.name" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formInline.status" placeholder="请选择状态" clearable style="width: 160px;">
            <el-option label="报名未开始" value="0" />
            <el-option label="报名进行中" value="1" />
            <el-option label="活动待开始" value="2" />
            <el-option label="活动进行中" value="3" />
            <el-option label="活动已结束" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="clear">重置</el-button>
          <el-button type="success" @click="addSeckill">新增秒杀活动</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <DataTable
        :table-data="tableData"
        :loading="loading"
        :total="total"
        @view="handleView"
        @edit="handleEdit"
        @delete="handleDelete"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <SeckillForm
      v-if="dialogVisible"
      v-model:visible="dialogVisible"
      :data="currentData"
      @success="handleFormSuccess"
    />

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="秒杀活动详情" width="600px">
      <el-form v-if="currentData" label-width="120px" :model="currentData">
        <el-form-item label="活动名称">
          <span>{{ currentData.seckillName }}</span>
        </el-form-item>

        <el-form-item label="活动状态">
          <el-tag :type="getStatusType(currentData.state)">
            {{ getStatusText(currentData.state) }}
          </el-tag>
        </el-form-item>

        <el-form-item label="活动内容">
          <span>{{ currentData.signStartTime }}</span>
        </el-form-item>

        <el-form-item label="报名开始时间">
          <span>{{ currentData.signStartTime }}</span>
        </el-form-item>

        <el-form-item label="报名结束时间">
          <span>{{ currentData.signEndTime }}</span>
        </el-form-item>

        <el-form-item label="活动开始时间">
          <span>{{ currentData.startTime }}</span>
        </el-form-item>

        <el-form-item label="活动结束时间">
          <span>{{ currentData.endTime }}</span>
        </el-form-item>

        <el-form-item label="是否需要保证金">
          <span>{{ currentData.ifBond === 1 ? '是' : '否' }}</span>
        </el-form-item>

        <el-form-item v-if="currentData.ifBond === 1" label="保证金金额">
          <span>{{ currentData.bondMoney }}</span>
        </el-form-item>

        <el-form-item label="优惠券是否叠加">
          <span>{{ currentData.ifAdd === 1 ? '是' : '否' }}</span>
        </el-form-item>

        <el-form-item label="商品限购">
          <span>{{ currentData.ifLimit === 1 ? '不限购' : '限购' }}</span>
        </el-form-item>

        <el-form-item v-if="currentData.ifLimit === 2" label="限购数量">
          <span>{{ currentData.limitNumber }}</span>
        </el-form-item>

        <el-form-item label="直降金额">
          <span>{{ currentData.seckillMoney }}</span>
        </el-form-item>

        <el-form-item label="商家数">
          <span>{{ currentData.shopNumber }}</span>
        </el-form-item>

        <el-form-item label="商品数量">
          <span>{{ currentData.productNumber }}</span>
        </el-form-item>

        <el-form-item label="备注">
          <span>{{ currentData.remark || '-' }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import DataTable from './component/dataTable.vue'
  import SeckillForm from './component/seckillForm.vue'
  import {
    getSeckillData,
    delSeckill,
    getSeckillDetail,
    addSeckill,
    editSeckill
  } from '@/api/active/active_seckill'
  import type { SeckillActivityItem } from '@/api/active/active_seckill'

  // 表单数据
  const formInline = ref({
    name: '',
    status: ''
  })

  // 表格数据
  const tableData = ref<SeckillActivityItem[]>([])
  const loading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  // 弹窗相关
  const dialogVisible = ref(false)
  const detailDialogVisible = ref(false)
  const currentData = ref<SeckillActivityItem | null>(null)
  const isEdit = ref(false)

  // 搜索
  const search = () => {
    currentPage.value = 1
    getSeckillListData()
  }

  // 清空搜索条件
  const clear = () => {
    formInline.value = {
      name: '',
      status: ''
    }
    currentPage.value = 1
    getSeckillListData()
  }

  // 新增秒杀活动
  const addSeckill = () => {
    isEdit.value = false
    currentData.value = null
    dialogVisible.value = true
  }

  // 查看详情
  const handleView = (row: SeckillActivityItem) => {
    loading.value = true
    getSeckillDetail({ seckillId: row.seckillId })
      .then((res: any) => {
        currentData.value = res.data
        detailDialogVisible.value = true
        loading.value = false
      })
      .catch(() => {
        ElMessage.error('获取详情失败')
        loading.value = false
      })
  }

  // 编辑
  const handleEdit = (row: SeckillActivityItem) => {
    isEdit.value = true
    loading.value = true
    getSeckillDetail({ seckillId: row.seckillId })
      .then((res: any) => {
        currentData.value = res.data
        dialogVisible.value = true
        loading.value = false
      })
      .catch(() => {
        ElMessage.error('获取详情失败')
        loading.value = false
      })
  }

  // 删除
  const handleDelete = (row: SeckillActivityItem) => {
    ElMessageBox.confirm('确定要删除该秒杀活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        delSeckill({ seckillId: row.seckillId })
          .then(() => {
            ElMessage.success('删除成功')
            getSeckillListData()
          })
          .catch(() => {
            ElMessage.error('删除失败')
          })
      })
      .catch(() => {
        // 取消删除
      })
  }

  // 处理分页大小变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    getSeckillListData()
  }

  // 处理当前页变化
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getSeckillListData()
  }

  // 获取秒杀活动列表
  const getSeckillListData = () => {
    loading.value = true
    const params = {
      seckillName: formInline.value.name,
      state: formInline.value.status ? parseInt(formInline.value.status) : undefined,
      page: currentPage.value,
      pageSize: pageSize.value
    }

    getSeckillData(params)
      .then((res: any) => {
        // 处理后端返回的数据，将其转换为前端需要的格式
        const list = res.data.list.map((item: any) => {
          // 如果后端返回的是组合时间字段，我们需要分解它们
          let signStartTime = ''
          let signEndTime = ''
          let startTime = ''
          let endTime = ''

          if (item.signTime && item.signTime.includes('~')) {
            const [start, end] = item.signTime.split('~')
            signStartTime = start
            signEndTime = end
          }

          if (item.time && item.time.includes('~')) {
            const [start, end] = item.time.split('~')
            startTime = start
            endTime = end
          }

          return {
            ...item,
            signStartTime,
            signEndTime,
            startTime,
            endTime,
            shopNumber: item.shops,
            productNumber: item.products
          }
        })

        tableData.value = list
        total.value = res.data.total
        loading.value = false
      })
      .catch(() => {
        loading.value = false
        ElMessage.error('获取秒杀活动列表失败')
      })
  }

  // 表单提交成功
  const handleFormSuccess = () => {
    if (isEdit.value) {
      // 编辑操作
      const formComponent = document.querySelector('seckill-form') as any
      if (formComponent && formComponent.getFormData) {
        const formData = formComponent.getFormData()
        editSeckill({
          ...formData,
          seckillId: currentData.value?.seckillId || 0
        })
          .then(() => {
            ElMessage.success('编辑成功')
            getSeckillListData()
          })
          .catch(() => {
            ElMessage.error('编辑失败')
          })
      }
    } else {
      // 新增操作
      const formComponent = document.querySelector('seckill-form') as any
      if (formComponent && formComponent.getFormData) {
        const formData = formComponent.getFormData()
        // 移除不需要的字段
        const { seckillId, state, shopNumber, productNumber, ...addData } = formData
        addSeckill(addData)
          .then(() => {
            ElMessage.success('新增成功')
            getSeckillListData()
          })
          .catch(() => {
            ElMessage.error('新增失败')
          })
      }
    }
  }

  // 获取状态文本
  const getStatusText = (status: number) => {
    const statusMap: Record<number, string> = {
      0: '报名未开始',
      1: '报名进行中',
      2: '活动待开始',
      3: '活动进行中',
      4: '活动已结束'
    }
    return statusMap[status] || '未知状态'
  }

  // 获取状态标签类型
  const getStatusType = (status: number) => {
    const typeMap: Record<number, 'info' | 'success' | 'warning' | 'danger' | ''> = {
      0: 'info',
      1: 'success',
      2: 'warning',
      3: 'success',
      4: 'danger'
    }
    return typeMap[status] || 'info'
  }

  onMounted(() => {
    getSeckillListData()
  })
</script>

<style scoped lang="scss">
  .seckill-list-container {
    padding: 20px;
    .search-card {
      margin-bottom: 20px;
    }
    .table-card {
      // 样式已在dataTable组件中定义
    }
  }
</style>
